package com.matrix.index.ui.home.fragment

import android.view.LayoutInflater
import androidx.fragment.app.viewModels
import com.chad.library.adapter.base.BaseQuickAdapter
import com.matrix.basecore.arouter.ARouterUtils
import com.matrix.basecore.base.BaseFragment
import com.matrix.index.R
import com.matrix.index.databinding.IndexJokeFragmentBinding
import com.matrix.index.net.IndexResult
import com.matrix.index.ui.home.adapter.RVJuheAdapter
import com.matrix.index.ui.home.bean.JuheJoke
import com.matrix.index.ui.home.bean.SearchBean
import com.matrix.index.ui.home.viewmodel.JokeVM

class IndexJokeFragment : BaseFragment<IndexJokeFragmentBinding>() {

    private val vm: JokeVM by viewModels()
    private lateinit var adapter: RVJuheAdapter
    private var juheJokes: MutableList<JuheJoke.Result> = mutableListOf()

    override fun getViewBinding(): IndexJokeFragmentBinding {
        return IndexJokeFragmentBinding.inflate(layoutInflater)
    }

    override fun initView(inflater: LayoutInflater) {
        adapter = RVJuheAdapter(R.layout.juhe_item_layout, juheJokes)
        mViewBinding.recyclerview.adapter = adapter
    }

    override fun initData() {
        vm.juheJoke().observe(this) { value ->
            value.run {
                if (value.code == IndexResult.SUCCESS) {
                    juheJokes.addAll((value.t as JuheJoke).result)
                    adapter.notifyDataSetChanged()
                    saveToDB(juheJokes)
                    adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
                }
                adapter.loadMoreModule.loadMoreComplete()
            }
        }
    }

    private fun saveToDB(juheJokes: MutableList<JuheJoke.Result>) {
        for (item in juheJokes) {
            var db = SearchBean(SearchBean.JOKE)
            db.jokeDesc = item.content
            db.timestamp = System.currentTimeMillis().toString()
            db.saveOrUpdate("jokeDesc = ?", item.content)
        }
    }

    override fun initListener() {
        adapter.loadMoreModule.setOnLoadMoreListener {
            initData()
        }
        adapter.setOnItemClickListener { adapter, view, position ->
            ARouterUtils.startJokePreviewActivity(juheJokes[position].content)
        }
    }
}